package com.swinw.asumall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.swinw.asumall.product.dao.BrandDao;
import com.swinw.asumall.product.entity.*;
import com.swinw.asumall.product.feign.CouponPriceFeignService;
import com.swinw.asumall.product.feign.SearchFeignService;
import com.swinw.asumall.product.feign.WarePriceFeignService;
import com.swinw.asumall.product.service.*;
import com.swinw.asumall.product.vo.*;
import com.swinw.common.to.SkuEsModel;
import com.swinw.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swinw.common.utils.PageUtils;
import com.swinw.common.utils.Query;

import com.swinw.asumall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService infoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;


    @Autowired
    CouponPriceFeignService couponPriceFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WarePriceFeignService warePriceFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    /**
     * 商品上架
     * 同一个Spu下的规格参数一样
     * 同一个spu下的sku品牌一样
     * 同一个Spu下的三级分类一样
     * @param spuId
     */
    @Transactional
    @Override
    public void upSpu(Long spuId) {

        //数据准备
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);

        //a、查询品牌信息
        BrandEntity brandEntity = brandService.selectById(spuInfoEntity.getBrandId());

        //b、查询分类信息
        CategoryEntity categoryEntity = categoryService.selectById(spuInfoEntity.getCatalogId());

        //c、查询spu对应的规格属性
        List<ProductAttrValueEntity> list = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<SkuEsModel.Attrs> spuArrtAndValue = list.stream().map(spuAttr -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            attrs.setAttrId(spuAttr.getAttrId());
            attrs.setAttrName(spuAttr.getAttrName());
            attrs.setAttrValue(spuAttr.getAttrValue());
            return attrs;
        }).collect(Collectors.toList());
        //1、查询当前Spu下的所有sku
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.selectSkuInfoBySpuId(spuId);

        //2、封装需要保存到ES的数据
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(skuInfo -> {
            SkuEsModel esModel = new SkuEsModel();
            esModel.setSpuId(skuInfo.getSpuId());
            esModel.setSkuId(skuInfo.getSkuId());
            esModel.setBrandId(skuInfo.getBrandId());
            if(brandEntity != null){
                esModel.setBrandName(brandEntity.getName());
                esModel.setBrandImg(brandEntity.getLogo());
            }
            esModel.setCatalogId(skuInfo.getCatalogId());
            if(categoryEntity != null){
                esModel.setCatalogName(categoryEntity.getName());
            }
            esModel.setSkuImg(skuInfo.getSkuDefaultImg());
            esModel.setSkuPrice(skuInfo.getPrice());
            esModel.setSkuTitle(skuInfo.getSkuTitle());
            esModel.setSaleCount(skuInfo.getSaleCount());
            esModel.setHotScore(99L);//热度得分
            R info = warePriceFeignService.selectByWareBySkuId(skuInfo.getSkuId());
            Map<String,Object> map = (Map<String, Object>) info.get("wareSku");
            if(map == null || map.size() == 0){
                esModel.setHasStock(false);//是否有库存
            }else{
                Object stock = map.get("stock");
                String s = stock.toString();
                if(!s.equals("0")){
                    esModel.setHasStock(true);//是否有库存
                }
            }
            esModel.setAttrs(spuArrtAndValue);
            return esModel;
        }).collect(Collectors.toList());

        //3、将数据保存到ES中
        R r = searchFeignService.saveSkuToEsAndUp(skuEsModels);
//        String code = (String) r.get("code");
        //4、修改spu的状态 publish_status 改为1,表示上架
        this.baseMapper.updatePublishStatus(spuId);
    }


    /**
     * 多条件查询
     * status: 状态
     * key: id 或者 spu_name
     * brandId: 品牌ID
     * catelogId: 商品ID
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String catelogld = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogld)){
            queryWrapper.eq("catalog_id",catelogld);
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);;
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
               wrapper.eq("id",key).or().like("spu_name",key);
            });
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 保存Spu信息
     *
     * @param spuSaveVo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1、保存Spu_info信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());//创建时间
        spuInfoEntity.setUpdateTime(new Date());//修改时间
        this.save(spuInfoEntity);

        //2、保存Spu的描述信息
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",spuSaveVo.getDecript()));
        infoDescService.saveInfo(spuInfoDescEntity);

        //3、保存Spu图片信息
        List<SpuImagesEntity> collect = spuSaveVo.getImages().stream().map(item -> {
            SpuImagesEntity imagesEntity = new SpuImagesEntity();
            imagesEntity.setSpuId(spuInfoEntity.getId());
            imagesEntity.setImgUrl(item);
            return imagesEntity;
        }).collect(Collectors.toList());
        imagesService.saveBatch(collect);

        //4、保存规格参数
        List<ProductAttrValueEntity> attrValueEntities = spuSaveVo.getBaseAttrs().stream().map((item) -> {
            AttrEntity byId = attrService.getById(item.getAttrId());
            ProductAttrValueEntity entity = new ProductAttrValueEntity();

            entity.setSpuId(spuInfoEntity.getId());
            entity.setAttrId(item.getAttrId());
            entity.setAttrValue(item.getAttrValues());
            entity.setAttrName(byId.getAttrName());

            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(attrValueEntities);

        //5、保存sku详细信息
        spuSaveVo.getSkus().forEach((sku)->{
            SkuInfoEntity skuEntity = new SkuInfoEntity();
            skuEntity.setSpuId(spuInfoEntity.getId());
            skuEntity.setBrandId(spuInfoEntity.getBrandId());
            skuEntity.setCatalogId(spuInfoEntity.getCatalogId());
            StringBuilder builder = new StringBuilder();
            List<String> descar = sku.getDescar();
            descar.forEach(item->{
                builder.append(item).append(",");
            });
            skuEntity.setSkuDesc(builder.toString());
            skuEntity.setPrice(sku.getPrice());
            skuEntity.setSkuName(sku.getSkuName());
            skuEntity.setSkuTitle(sku.getSkuTitle());
            skuEntity.setSkuSubtitle(sku.getSkuSubtitle());
            List<Images> images = sku.getImages();
            images.forEach((item)->{

                if(item.getDefaultImg() == 1){
                    skuEntity.setSkuDefaultImg(item.getImgUrl());
                }
            });
            skuEntity.setSaleCount(0L);
            skuInfoService.save(skuEntity);

            //6、添加Sku图片信息
            List<SkuImagesEntity> imagesEntityList = images.stream().map((item) -> {
                SkuImagesEntity imagesEntity = new SkuImagesEntity();
                imagesEntity.setDefaultImg(item.getDefaultImg());
                imagesEntity.setImgUrl(item.getImgUrl());
                imagesEntity.setSkuId(skuEntity.getSkuId());
                imagesEntity.setImgSort(0);
                return imagesEntity;
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(imagesEntityList);

            //7、保存销售属性信息
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = sku.getAttr().stream().map((item) -> {
                SkuSaleAttrValueEntity entity = new SkuSaleAttrValueEntity();
                entity.setSkuId(skuEntity.getSkuId());
                entity.setAttrId(item.getAttrId());
                entity.setAttrName(item.getAttrName());
                entity.setAttrValue(item.getAttrValue());
                entity.setAttrSort(0);
                return entity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            //8、保存优惠价格信息
            SkuLadderEntity ladderEntity = new SkuLadderEntity();
            ladderEntity.setSkuId(skuEntity.getSkuId());
            ladderEntity.setFullCount(sku.getFullCount());
            ladderEntity.setDiscount(sku.getDiscount());
            ladderEntity.setAddOther(sku.getCountStatus());
            couponPriceFeignService.save(ladderEntity);

            //9、保存满减信息
            SkuFullReductionEntity reductionEntity = new SkuFullReductionEntity();
            reductionEntity.setSkuId(skuEntity.getSkuId());
            reductionEntity.setAddOther(sku.getPriceStatus());
            reductionEntity.setFullPrice(sku.getFullPrice());
            reductionEntity.setReducePrice(sku.getReducePrice());
            couponPriceFeignService.save(reductionEntity);

            //10、保存会员价信息
            sku.getMemberPrice().forEach((item)->{
                MemberPriceEntity priceEntity = new MemberPriceEntity();
                priceEntity.setMemberLevelName(item.getName());
                priceEntity.setSkuId(skuEntity.getSkuId());
                priceEntity.setAddOther(0);
                priceEntity.setMemberPrice(item.getPrice());
                priceEntity.setMemberLevelId(getMemberLave(item.getName()));

                couponPriceFeignService.save(priceEntity);
            });

        });
        //11、保存积分信息
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsEntity spuBoundsEntity = new SpuBoundsEntity();
        spuBoundsEntity.setBuyBounds(bounds.getBuyBounds());
        spuBoundsEntity.setGrowBounds(bounds.getGrowBounds());
        spuBoundsEntity.setSpuId(spuInfoEntity.getId());
        couponPriceFeignService.save(spuBoundsEntity);
    }


    private Long getMemberLave(String name) {
        Long lave = 0L;
        switch (name){
            case "普通会员":
                lave = 1L;
                break;
            case "白银会员":
                lave = 2L;
                break;
            case "黄金会员":
                lave = 3L;
                break;
            case "铂金会员":
                lave = 4L;
                break;
            default :
                lave = 5L;
                break;
        }
        return lave;
    }

}